<template>
  <el-dialog
    width="1200px"
    :title="$t('m.sigin.sigin')"
    :visible.sync="popupVisible"
    :before-close="close"
    :close-on-click-modal="false"
    v-loading="dialogLoading">
    <!-- 根据通知单号返显明细 start-->
    <el-form align="left" ref="form" :model="detail" label-width="120px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="sku">
            <el-input maxlength="20" show-word-limit v-model="detail.productspeccode" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="supplierCode">
            <el-input maxlength="20" show-word-limit v-model="detail.suppliercode" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('m.in.productspec')">
            <el-input maxlength="20" show-word-limit v-model="detail.productspec" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('m.in.productname')">
            <el-input maxlength="20" show-word-limit v-model="detail.productname" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" justify="end">
        <el-col :span="8" v-if="!completed">
          <el-form-item :label="$t('m.sigin.sigin')+$t('m.sigin.signquantity')">
            <el-input maxlength="20" show-word-limit v-model.number.trim="amount" :disabled="completed" @blur="checkAmount"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="!completed">
          <el-form-item :label="$t('m.sigin.tsareacode')">
              <el-select
                v-model="tsareaid"
                filterable
                :label="$t('m.choose')+$t('m.sigin.tsareacode')">
                <el-option
                  v-for="(item,index) in tsareaData"
                  :key="index"
                  :label="item.code"
                  :value="item.id"
                  :disabled="item.selected"
                ></el-option>
              </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 根据通知单号查询明细 end-->

    <!-- table start -->
    <el-row>
      <el-col :span="24">
         <el-table
          ref="table"
          stripe
          empty-text
          fit
          tooltip-effect="dark"
          :data="tableData">
          <el-table-column align="center" type="index" :label="$t('m.index')" width="50"></el-table-column>
          <el-table-column align="center" :label="$t('m.sigin.signquantity')">
            <template slot-scope="scope">
              <el-input maxlength="20" show-word-limit v-model.number="scope.row.signquantity" :disabled="completed"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('m.sigin.productiondate')" width="250">
            <template slot-scope="scope">
              <template v-if="isProductiondate">
                <el-date-picker
                  v-model="scope.row.productiondate"
                  type="date"
                  :placeholder="$t('m.in.choosedate')"
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions"
                  @change="pickTime(scope.$index)"
                ></el-date-picker>
              </template>
              <template v-else>
                <el-date-picker :placeholder="$t('m.sigin.nodate')" disabled></el-date-picker>
              </template>
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('m.sigin.expirydate')">
            <template slot-scope="scope">
              <el-input maxlength="20" show-word-limit v-model="scope.row.expirydate" disabled></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('m.sigin.containertype')">
            <template slot-scope="scope">
              <el-input maxlength="20" show-word-limit v-model="scope.row.containertypename" disabled></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('m.page.container')+$t('m.code')">
            <template slot-scope="scope">
              <template v-if="completed">
                <el-select v-model="scope.row.containercode" disabled></el-select>
              </template>
              <template v-else>
                <el-select
                  v-model="scope.row.containerid"
                  filterable
                  :label="$t('m.choose')"
                  clearable
                  @change="(id)=>{triggerSelect(id,scope.$index,'containerData')}">
                  <el-option
                    v-for="(item,index) in containerData"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                    :disabled="item.selected"
                  ></el-option>
                </el-select>
              </template>
            </template>
          </el-table-column>
          <template v-if="completed">
            <el-table-column align="center" :label="$t('m.sigin.tsareacode')" prop="tsareacode"></el-table-column>
          </template>
          <template v-if="!completed">
            <el-table-column align="center" :label="$t('m.operation')">
              <template slot-scope="scope">
                <i
                  class="el-icon-remove-outline remove-icon"
                  @click="remove(scope.$index)"
                  v-if="tableData.length>1"
                ></i>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </el-col>
    </el-row>
    <!-- table end -->
    <el-row>
      <el-col :span="8" align="left" v-show="!completed">
        <el-button type="primary" @click="addContainer">{{$t('m.add')+$t('m.page.container')}}</el-button>
      </el-col>
      <el-col :span="completed?24:16" :align="completed?'center':'right'">
        <el-button type="primary" @click="save" v-show="!completed">{{$t('m.save')}}</el-button>
        <el-button @click="close">{{$t('m.close')}}</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>
<script>
import common from '@/utils/common'
import { getLodop } from '@/utils/LodopFuncs'
export default {
  name:'signing-add-popup',
  props:['popupVisible', 'arrivalnoticeDetail'],
  data(){
    return {
      detail:{},

      amount:0, // 理货数量
      tsareaid:'', // 暂存区id

      tableData:[],
      tableDataItem:{
        signquantity:0, // 数量
        containerid:'', // 容器id
        containercode:'', // 容器号
        containertypeid:'', // 容器类型id
        containertypename:'', // 容器类型
        productiondate:'', // 生产日期
        expirydate:'', // 到期日期
        action:'add'
      },

      isProductiondate:false, // 商品是否存在生产日期
      containerData:[], // 初始化容器列表
      tsareaData:[], // 初始化暂存位置列表

      pickerOptions:{
        disabledDate(time){
          return time.getTime() > Date.now()
        }
      },
      dialogLoading:false
    }
  },
  mounted(){
    this.tableData.push(this.cloneObject(this.tableDataItem))
    this.getData(this.initFn)
    // 如果是查看的情况下，没必要调这两个接口
    if (!this.completed){
      this.getTsarea()
      this.getContainer()
    }
  },
  computed:{
    // 满足已到货数量===计划到货数量 true : 查看 ; false : 理货
    completed(){
      return this.arrivalnoticeDetail.completed
    },
    // 根据暂存区id，返回暂存区名字
    tsareaname(){
      let {name} = this.tsareaData.find((item)=>{
        return item.id === this.tsareaid
      })
      return name
    }
  },
  methods:{
    close(){
      this.$emit('close')
    },
    // 根据理货单号&&sku获取理货明细
    getData(callback){
      let { noticenumber, sku } = this.arrivalnoticeDetail
      let singUrl = `/arrivalnotice/getdetail/${noticenumber}/${sku}` // 理货操作api
      let checkUrl = `/signin/getdetailwithitems/${noticenumber}/${sku}` // 查看理货明细api
      let url = this.completed ? checkUrl : singUrl

      let options = {
        method:'get',
        url
      }
      this.$axios(options).then(({ data }) => {
        this.detail = data
        callback && callback(this.detail.actualquantity1)
      })
    },
    // 初始化获取数据时执行
    initFn(){
      if (this.completed){
        // 数量已达标
        this.amount =
          this.detail.plannedquantityfs - this.detail.actualquantity1 || 0
        this.tableData = this.detail.signindetailitemList
      } else {
        // 数量未达标
        this.tableData[0].signquantity =
          this.amount = 'actualquantity1' in this.detail?this.detail.actualquantity1:this.detail.plannedquantityfs
        this.isProductiondate = this.detail.isProductiondate
      }
    },
    checkAmount(){
      if (this.amount <= 0){
        this.callbackMessage(this.$t('m.sigin.checkamount'))
        return false
      }
      return true
    },
    // 获取容器区列表
    getContainer(){
      let options = {
        method:'get',
        url:`/container/list`
      }
      this.$axios(options).then(({ data }) => {
        for (let i = 0; i < data.length; i++){
          let { containercode:code, containerid:id, containercode:name, containertype, containertypeid } = data[i]
          this.containerData.push({code, id, name, containertype, containertypeid, selected:false})
        }
      })
    },
    // 获取暂存区列表
    getTsarea(){
      let options = {
        method:'get',
        url:`/tsarea/list`
      }
      this.$axios(options).then(({ data }) => {
        for (let i = 0; i < data.length; i++){
          if(data[i].type===1){
            let { tsareacode:code, tsareaid:id, tsareaname:name } = data[i]
            this.tsareaData.push({code, id, name})
          }
        }
      })
    },
    // 选择生产日期后触发的event
    pickTime(index){
      // 如果存在过期时间
      if (this.detail.isexpiration){
        let expirationnum = this.detail.expirationnum // 离生产日期还有expirationnum日过期
        let limitationofreceipt = this.detail.limitationofreceipt // 禁收limitationofreceipt日
        let millisecond = 24 * 3600 * 1000 // 1天等于86400000毫秒

        let productionTimestamp = this.timeToTimestamp(this.tableData[index].productiondate) // 生产日期的时间戳
        let expiryTimestamp = productionTimestamp + millisecond * expirationnum // 到期日期的时间戳

        let todayTimestamp = new Date(
          this.formatTodayTimestamp(new Date())
        ).getTime() // 今日的时间戳(返回yyyy-MM-dd的时间戳)
        let limitationoTimestamp = todayTimestamp - millisecond * limitationofreceipt // 禁收日期的时间戳

        if (productionTimestamp > limitationoTimestamp){
          // 生产日期大于禁收日期，才能通过
          this.tableData[index].expirydate = common.timestampSimple(
            expiryTimestamp
          )
        } else {
          this.callbackMessage(this.$t('m.sigin.overdate'))
          this.tableData[index].productiondate = this.tableData[
            index
          ].expirydate = ''
        }
      }
    },
    // 下拉框选中后触发的event
    triggerSelect(id, index, arrName){
      let containertype = ''
      let containertypeid = ''
      if(id){
        let result = this.containerData.find((item)=>item.id === id)
        containertype = result.containertype
        containertypeid = result.containertypeid
      }

      this.$set(this.tableData[index],'containertypename',containertype)
      this.$set(this.tableData[index],'containertypeid',containertypeid)
      // 重置选中状态
      for (let i = 0; i < this[arrName].length; i++){
        this[arrName][i].selected = false
      }
      let name = arrName.slice(0, -4)
      // 根据tableData修改已被选中的状态
      for (let i = 0; i < this.tableData.length; i++){
        for (let j = 0; j < this[arrName].length; j++){
          if (this.tableData[i][name + 'id'] === this[arrName][j].id){
            this.tableData[i][name + 'code'] = this[arrName][j].code
            this[arrName][j].selected = true
            continue
          }
        }
      }
    },
    // 删除table选中项
    remove(index){
      if (this.tableData.length === 1) return
      this.$delete(this.tableData, index)
      // 重置选中状态
      for (let i = 0; i < this.containerData.length; i++){
        this.containerData[i].selected = false
      }
      // 根据tableData修改已被选中的状态
      for (let i = 0; i < this.tableData.length; i++){
        for (let j = 0; j < this.containerData.length; j++){
          if (this.tableData[i].containerid === this.containerData[j].id){
            this.containerData[j].selected = true
            continue
          }
        }
      }
    },
    // table增加一项
    addContainer(){
      let totalAmount = 0
      for (let i = 0; i < this.tableData.length; i++){
        if (this.tableData[i].signquantity <= 0)
          return this.callbackMessage(this.$t('m.enter')+this.$t('m.check.count'))
        totalAmount += parseInt(this.tableData[i].signquantity)
      }
      if(totalAmount>=this.amount)
        return this.callbackMessage(this.$t('m.sigin.overcount'))
      let item = this.cloneObject(this.tableDataItem)
      let currentAmount = 0
      for (let i = 0; i < this.tableData.length; i++){
        currentAmount += this.tableData[i].signquantity
      }
      // 【数量】优化计算
      let surplus = this.amount - currentAmount
      let prev = this.tableData[this.tableData.length - 1].signquantity
      item.signquantity =
        surplus >= prev ? (prev === 0 ? surplus : prev) : surplus

      // 如果上一项有填写日期，默认取上一项的日期
      let productiondate = this.tableData[this.tableData.length - 1]
        .productiondate
      if (productiondate){
        item.productiondate = productiondate
        if (this.detail.isexpiration)
          item.expirydate = this.tableData[
            this.tableData.length - 1
          ].expirydate
      }
      this.tableData.push(item)
    },
    save(){
      if (!this.checkAmount()) return false
      // 1.判断tableData中signquantity的和是否等于到货数量
      let totalAmount = 0
      for (let i = 0; i < this.tableData.length; i++){
        if (this.tableData[i].signquantity <= 0)
          return this.callbackMessage(this.$t('m.enter')+this.$t('m.check.count'))
        totalAmount += parseInt(this.tableData[i].signquantity)
      }
      if(isNaN(this.amount))
        return this.callbackMessage(this.$t('m.enter')+this.$t('m.check.count'))
      if (totalAmount !== this.amount)
        return this.callbackMessage(this.$t('m.sigin.equal'))
      // 2.用户修改过到货数量，到货数量不能 > 计划到货数量 - 已到货数量
      let actualAmount = 'actualquantity1' in this.detail?this.detail.actualquantity1:this.detail.plannedquantityfs
      if (this.amount > actualAmount)
        return this.callbackMessage(`到货数量不能大于${actualAmount}`)
      // 3.判断是否漏选了暂存位置
      if(!this.tsareaid)
        return this.callbackMessage(this.$t('m.sigin.checktemporary'))
      // 4.如果该商品有生产日期，判断是否有漏填项
      if (this.detail.isProductiondate){
        for (let i = 0; i < this.tableData.length; i++){
          if (this.tableData[i].productiondate === ''){
            return this.callbackMessage(this.$t('m.choose')+this.$t('m.sigin.productiondate'))
          }
        }
      }

      let { noticenumber, sku } = this.arrivalnoticeDetail
      let {code:tsareacode} = this.tsareaData.find((item)=>{
        return item.id === this.tsareaid
      })
      let options = {
        method:'put',
        url:`/signin/adddetailitem/${noticenumber}/${sku}`,
        params:{
          actualquantity:this.amount,
          tsareacode,
          tsareaid:this.tsareaid
        },
        data:this.tableData
      }
      this.dialogLoading = true
      this.$axios(options).then(({ data,message }) => {
        // 成功后回调上个弹窗的接口，返回已到货数量
        this.callbackMessage(message,'success',1500,()=>{
          this.dialogLoading = false
          this.getData(this.endFn)
          let arr = []
          // 触发打印模板
          data.forEach(v => {
            arr.push(v.tasknumber)
          })
          this.print(arr)
        })
      }).catch(()=>{
        this.dialogLoading = false
      })
    },
    // 理货成功后获取已到货数量
    endFn(restAmount){
      this.$emit('callback', restAmount) // 更新数值-->（已到货数量）
      this.$emit('close')
    },
    print(arr){
      let LODOP = getLodop()
      let that = this
      that
        .$axios({
          method:'post',
          url:'/printtemplate/printsign',
          data:arr
        })
        .then(({data})=> {
          that.printContent = data
          // that.printContent +=
          //   'LODOP.SET_PRINT_PAGESIZE(1, "50mm", "30mm", "");LODOP.PREVIEW();';
          eval(that.printContent)
          LODOP.SET_PRINT_PAGESIZE(1, '50mm', '30mm', '')
          LODOP.PREVIEW()
        })
    },
    timeToTimestamp(time){
      let timestamp = new Date(time).getTime()
      return timestamp
    },
    formatTodayTimestamp(timestamp){
      let year = timestamp.getFullYear()
      let month = timestamp.getMonth() + 1
      if (month < 10) month = '0' + month
      let day = timestamp.getDate()
      if (day < 10) day = '0' + day
      return `${year}-${month}-${day}`
    }
  }
}
</script>
<style lang="scss" scoped>
.remove-icon {
  font-size: 30px;
  color: red;
  cursor: pointer;
}
.el-select{width: 100%;}
</style>